/**
 * 
 */
package net.ddns.heroli.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.service.HeroService;
import cn.com.gzheroli.core.manager.Client;
import cn.com.gzheroli.core.util.FileUtils;
import net.coobird.thumbnailator.Thumbnails;
import net.ddns.heroli.pojo.TBAttachment;
import net.ddns.heroli.service.AttachMentService;

/**  
* 类名: CommonController  
* 描述: TODO(这里用一句话描述这个类的作用)  
* 作者: 李长荣 lichang_20011@163.com  
* 日期: 2017年12月19日  下午8:28:28
*@version V1.0  
*    
*/
@Controller
@RequestMapping("/api/attachMentController")
public class AttachMentController {
	private static final Logger logger = LoggerFactory.getLogger(AttachMentController.class);
	@Autowired
    private SpringRedisCache cache;
	@Autowired
	private HeroService heroService;
	@Autowired
	AttachMentService attachMentService;
	@Autowired
    CommonsMultipartResolver multipartResolver;
	/**
	 * 
	* @Title: uploadAttachBase64 
	* @Description:上传报告base64图片
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "uploadAttachBase64")
	@ResponseBody
	public  AjaxJson uploadAttachBase64( HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		Map dicMap=new HashMap();
		/*String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("未登陆!");
			return j;
		}
		TSUser user=client.getUser();*/
		String id=request.getParameter("id")==null?"":request.getParameter("id");
		if(id.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("业务主键id不能为空!");
			return j;
		}
		String type=request.getParameter("type")==null?"":request.getParameter("type");
		String fileName=request.getParameter("fileName")==null?"":request.getParameter("fileName");
		String remark=request.getParameter("remark")==null?"":request.getParameter("remark");
		String tag=request.getParameter("tag")==null?"":request.getParameter("tag");//word中书签名称
		String tableName=request.getParameter("tableName")==null?"":request.getParameter("tableName");//
		int maxWidth=request.getParameter("maxWidth")==null?100:Integer.parseInt(request.getParameter("maxWidth"));
		String base64Code = request.getParameter("base64Code");//base64串
		String attachMentPath="";
        if(base64Code != null&&!base64Code.trim().equals("")){
            //如果名称不为“”,说明该文件存在，否则说明该文件不存在
            if(!fileName.trim().equals("")){
            	fileName=fileName+".jpg";
                System.out.println(fileName);
                
                FileUtils.judeDirExists(new File(request.getSession().getServletContext().getRealPath("/upload/")));
                String filePath=request.getSession().getServletContext().getRealPath("/upload/")+"/"+id+"/" ; 
                FileUtils.judeDirExists(new File(filePath));
                //定义上传路径
                String path = filePath+fileName;
                File localFile = new File(path);
                String realPath="/upload/"+id+"/" +fileName;
                Base64 base64 = new Base64();
                //BASE64Decoder decoder = new BASE64Decoder();              
        		byte[] bytes = base64.decodeBase64(new String(base64Code).getBytes()); 		
				try { 
//					byte[] bytes = decoder.decodeBuffer(base64Code); 
//					ByteArrayInputStream in = new ByteArrayInputStream(bytes);  
//		            BufferedImage bi =ImageIO.read(in);
//		            File file=new File(path);
//		            ImageIO.write(bi, "jpg", file);//不管输出什么格式图片，此处不需改动
					ByteArrayInputStream in = new ByteArrayInputStream(bytes); 
		            byte[] buffer = new byte[1024];  
		            FileOutputStream out = new FileOutputStream(path);  
		            int bytesum = 0;  
		            int byteread = 0;  
		            while ((byteread = in.read(buffer)) != -1) {  
		                bytesum += byteread;  
		                out.write(buffer, 0, byteread); // 文件写操作  
		                out.flush();  
		            }  
		            out.close(); 
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}  
                 
                String extName=FileUtils.getExtend(fileName);
                Map paraMap=new HashMap();
                paraMap.put("businessKey", id);
                paraMap.put("fileName", fileName);
                paraMap.put("remark", remark);
                paraMap.put("tag", tag);
                paraMap.put("type", type);
                List<Map<String,Object>> attachMents=attachMentService.getAttachment(paraMap);
                if(attachMents!=null&&!attachMents.isEmpty()){
                	//TBAttachment attachMent=attachMents.get(0);
                	
                }else{
                	TBAttachment attachMent=new TBAttachment();
                    attachMent.setBusinessKey(id);
                    attachMent.setCreateDate(new Date());
                    attachMent.setExtName(extName);
                    attachMent.setRealPath(realPath);
                    //attachMent.setUserId(user.getId());
                    attachMent.setType(type);
                    attachMent.setFileName(fileName);
                    attachMent.setRemark(remark);
                    attachMent.setTag(tag);
                    attachMent.setTableName(tableName);
                    attachMent.setMaxWidth((new Double(maxWidth*19.95)).intValue());
                    heroService.save(attachMent);
                }
                attachMentPath="/upload/"+id+"/" +fileName;
            }
        }
        //记录上传该文件后的时间
        int finaltime = (int) System.currentTimeMillis();
        //System.out.println(finaltime - pre);
		j.setObj(attachMentPath);
		j.setSuccess(true);
		j.setMsg("上传成功!");
		return j;
	}
	/**
	 * 
	* @Title uploadImageSingle 
	* @Description 上传单个文件
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "uploadImageSingle")
	@ResponseBody
	public  AjaxJson uploadImageSingle( HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		Map dicMap=new HashMap();
		String tableName=request.getParameter("tableName")==null?"":request.getParameter("tableName");//业务表名
		String id=request.getParameter("id")==null?"":request.getParameter("id");//附件表id
		String businessKey=request.getParameter("businessKey")==null?"":request.getParameter("businessKey");//业务表主键id
		String isAdd=request.getParameter("isAdd")==null?"1":request.getParameter("isAdd");
		String suffix=request.getParameter("suffix")==null?"s":request.getParameter("suffix");//缩略图 后缀
		String isScal=request.getParameter("isScal")==null?"1":request.getParameter("isScal");//是否按大小缩放 1:是 0:否
		String scal=request.getParameter("scal")==null?"0.485":request.getParameter("scal");//缩放比例
		String width=request.getParameter("width")==null?"300":request.getParameter("width");//缩放宽度
		String height=request.getParameter("height")==null?"300":request.getParameter("height");//缩放高度
		if(businessKey.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("业务主键id不能为空!");
			return j;
		}
		String type=request.getParameter("type")==null?"":request.getParameter("type");//类别
		String remark=request.getParameter("remark")==null?"":request.getParameter("remark");//备注
		String tag=request.getParameter("tag")==null?"":request.getParameter("tag");//标签名称
		int maxWidth=request.getParameter("maxWidth")==null?1200:Integer.parseInt(request.getParameter("maxWidth"));
		List attachMentPath=new ArrayList();
		//判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //记录上传过程起始时的时间，用来计算上传时间
                int pre = (int) System.currentTimeMillis();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if(myFileName.trim() !=""){
                        System.out.println(myFileName);
                        //重命名上传后的文件名
                        String fileName = file.getOriginalFilename();
                        
                        FileUtils.judeDirExists(new File(request.getSession().getServletContext().getRealPath("/upload/")));
                        String filePath=request.getSession().getServletContext().getRealPath("/upload/")+"/"+id+"/" ; 
                        FileUtils.judeDirExists(new File(filePath));
                        //定义上传路径
                        String path = filePath+fileName;
                        File localFile = new File(path);
                        String extName=FileUtils.getExtend(fileName);
                        try {
                            file.transferTo(localFile);
                            if(isScal.equals("1")) {
                            	Thumbnails.of(path)   
                                .size(Integer.parseInt(width), Integer.parseInt(height))  
                                .toFile(filePath+fileName.replace("."+extName, "-"+suffix+"."+extName)); 
                            }else {
                            	Thumbnails.of(path)   
                                .scale(Double.parseDouble(scal))  
                                .toFile(filePath+fileName.replace("."+extName, "-"+suffix+"."+extName)); 
                            }
                            
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        String realPath="/upload/"+id+"/" +fileName;
                        if(id!=null&&!id.trim().equals("")){
                        	Map paraMap=new HashMap();
                        		paraMap.put("id", id);
                            paraMap.put("businessKey", businessKey);
                            paraMap.put("fileName", fileName);
                            paraMap.put("remark", remark);
                            paraMap.put("tag", tag);
                            paraMap.put("type", type);
                            paraMap.put("fileName", fileName);
                            paraMap.put("realPath", realPath);
                            paraMap.put("extName", extName);
                            paraMap.put("maxWidth", maxWidth);
                        		heroService.updateMap("T_B_ATTACHMENT", paraMap, null, TBAttachment.class);
                        }else{
                        	   TBAttachment attachMent=new TBAttachment();
                            attachMent.setBusinessKey(businessKey);
                            attachMent.setCreateDate(new Date());
                            attachMent.setExtName(extName);
                            attachMent.setRealPath(realPath);
                            //attachMent.setUserId(user.getId());
                            attachMent.setType(type);
                            attachMent.setFileName(fileName);
                            attachMent.setRemark(remark);
                            attachMent.setTag(tag);
                            attachMent.setTableName(tableName);
                            attachMent.setMaxWidth(maxWidth);
                            heroService.save(attachMent);
                        }
                        attachMentPath.add("/upload/"+id+"/" +fileName);
                        break;
                    }
                }
                //记录上传该文件后的时间
                int finaltime = (int) System.currentTimeMillis();
                System.out.println(finaltime - pre);
            }
        }
		j.setObj(attachMentPath);
		j.setSuccess(true);
		j.setMsg("上传成功!");
		return j;
	}
	@RequestMapping(value = "uploadImage")
	@ResponseBody
	public  AjaxJson uploadImage( HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		Map dicMap=new HashMap();
		/*String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("未登陆!");
			return j;
		}
		TSUser user=client.getUser();*/
		String tableName=request.getParameter("tableName")==null?"":request.getParameter("tableName");//业务表名
		String id=request.getParameter("id")==null?"":request.getParameter("id");
		String suffix=request.getParameter("suffix")==null?"s":request.getParameter("suffix");//缩略图 后缀
		String isScal=request.getParameter("isScal")==null?"1":request.getParameter("isScal");//是否按大小缩放 1:是 0:否
		String scal=request.getParameter("scal")==null?"0.485":request.getParameter("scal");//缩放比例
		String width=request.getParameter("width")==null?"300":request.getParameter("width");//缩放宽度
		String height=request.getParameter("height")==null?"300":request.getParameter("height");//缩放高度
		if(id.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("业务主键id不能为空!");
			return j;
		}
		String type=request.getParameter("type")==null?"":request.getParameter("type");//类别
		String remark=request.getParameter("remark")==null?"":request.getParameter("remark");//备注
		String tag=request.getParameter("tag")==null?"":request.getParameter("tag");//标签名称
		int maxWidth=request.getParameter("maxWidth")==null?1200:Integer.parseInt(request.getParameter("maxWidth"));
		List attachMentPath=new ArrayList();
		//判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //记录上传过程起始时的时间，用来计算上传时间
                int pre = (int) System.currentTimeMillis();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if(myFileName.trim() !=""){
                        System.out.println(myFileName);
                        //重命名上传后的文件名
                        String fileName = file.getOriginalFilename();
                        
                        FileUtils.judeDirExists(new File(request.getSession().getServletContext().getRealPath("/upload/")));
                        String filePath=request.getSession().getServletContext().getRealPath("/upload/")+"/"+id+"/" ; 
                        FileUtils.judeDirExists(new File(filePath));
                        //定义上传路径
//                        String path = "H:/" + fileName;
                        String path = filePath+fileName;
                        File localFile = new File(path);
                        String extName=FileUtils.getExtend(fileName);
                        try {
                            file.transferTo(localFile);
                            if(isScal.equals("1")) {
                            	Thumbnails.of(path)   
                                .size(Integer.parseInt(width), Integer.parseInt(height))  
                                .toFile(filePath+fileName.replace("."+extName, "-"+suffix+"."+extName)); 
                            }else {
                            	Thumbnails.of(path)   
                                .scale(Double.parseDouble(scal))  
                                .toFile(filePath+fileName.replace("."+extName, "-"+suffix+"."+extName)); 
                            }
                            
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        String realPath="/upload/"+id+"/" +fileName;
                        /*if(type.equals("初评报告")||type.equals("终评报告")){
                        	realPath="/template/"+id+"/" +fileName;
                        }*/
                        
                        Map paraMap=new HashMap();
                        paraMap.put("businessKey", id);
                        paraMap.put("fileName", fileName);
                        paraMap.put("remark", remark);
                        paraMap.put("tag", tag);
                        paraMap.put("type", type);
                        List<Map<String,Object>> attachMents=attachMentService.getAttachment(paraMap);
                        if(attachMents!=null&&!attachMents.isEmpty()){
                        	//TBAttachment attachMent=attachMents.get(0);
                        	
                        }else{
                        	TBAttachment attachMent=new TBAttachment();
                            attachMent.setBusinessKey(id);
                            attachMent.setCreateDate(new Date());
                            attachMent.setExtName(extName);
                            attachMent.setRealPath(realPath);
                            //attachMent.setUserId(user.getId());
                            attachMent.setType(type);
                            attachMent.setFileName(fileName);
                            attachMent.setRemark(remark);
                            attachMent.setTag(tag);
                            attachMent.setTableName(tableName);
                            attachMent.setMaxWidth(maxWidth);
                            heroService.save(attachMent);
                        }
                        attachMentPath.add("/upload/"+id+"/" +fileName);
                    }
                }
                //记录上传该文件后的时间
                int finaltime = (int) System.currentTimeMillis();
                System.out.println(finaltime - pre);
            }
        }
		j.setObj(attachMentPath);
		j.setSuccess(true);
		j.setMsg("上传成功!");
		return j;
	}
	/**
	 * 
	* @Title: uploadAttachMent 
	* @Description: 上传附件
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "uploadAttachMent")
	@ResponseBody
	public  AjaxJson uploadAttachMent( HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		Map dicMap=new HashMap();
		/*String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("未登陆!");
			return j;
		}
		TSUser user=client.getUser();*/
		String tableName=request.getParameter("tableName")==null?"":request.getParameter("tableName");//
		String id=request.getParameter("id")==null?"":request.getParameter("id");
		if(id.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("业务主键id不能为空!");
			return j;
		}
		String type=request.getParameter("type")==null?"":request.getParameter("type");
		String remark=request.getParameter("remark")==null?"":request.getParameter("remark");
		String tag=request.getParameter("tag")==null?"":request.getParameter("tag");//word中书签名称
		int maxWidth=request.getParameter("maxWidth")==null?1200:Integer.parseInt(request.getParameter("maxWidth"));
		
		//TPBasebusiness tpbasebus = commonService.get(TPBasebusiness.class,id);
		List attachMentPath=new ArrayList();
		//判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //记录上传过程起始时的时间，用来计算上传时间
                int pre = (int) System.currentTimeMillis();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if(myFileName.trim() !=""){
                        System.out.println(myFileName);
                        //重命名上传后的文件名
                        String fileName = file.getOriginalFilename();
                        
                        FileUtils.judeDirExists(new File(request.getSession().getServletContext().getRealPath("/upload/")));
                        String filePath=request.getSession().getServletContext().getRealPath("/upload/")+"/"+id+"/" ; 
                        if(type.equals("初评报告")){
                        	fileName="初评报告.docx";	
                        }else if(type.equals("终评报告")){
                        	fileName="终评报告.docx";
                        }
                        FileUtils.judeDirExists(new File(filePath));
                        //定义上传路径
//                        String path = "H:/" + fileName;
                        String path = filePath+fileName;
                        File localFile = new File(path);
                        try {
                            file.transferTo(localFile);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        String realPath="/upload/"+id+"/" +fileName;
                        /*if(type.equals("初评报告")||type.equals("终评报告")){
                        	realPath="/template/"+id+"/" +fileName;
                        }*/
                        String extName=FileUtils.getExtend(fileName);
                        Map paraMap=new HashMap();
                        paraMap.put("businessKey", id);
                        paraMap.put("fileName", fileName);
                        paraMap.put("remark", remark);
                        paraMap.put("tag", tag);
                        paraMap.put("type", type);
                        List<Map<String,Object>> attachMents=attachMentService.getAttachment(paraMap);
                        if(attachMents!=null&&!attachMents.isEmpty()){
                        	//TBAttachment attachMent=attachMents.get(0);
                        	
                        }else{
                        	TBAttachment attachMent=new TBAttachment();
                            attachMent.setBusinessKey(id);
                            attachMent.setCreateDate(new Date());
                            attachMent.setExtName(extName);
                            attachMent.setRealPath(realPath);
                            //attachMent.setUserId(user.getId());
                            attachMent.setType(type);
                            attachMent.setFileName(fileName);
                            attachMent.setRemark(remark);
                            attachMent.setTag(tag);
                            attachMent.setTableName(tableName);
                            attachMent.setMaxWidth(maxWidth);
                            heroService.save(attachMent);
                        }
                        /*if(type.equals("初评报告")||type.equals("终评报告")){
                        	attachMentPath.add("/template/"+id+"/" +fileName);
                        }else{
                        	attachMentPath.add("/upload/"+id+"/" +fileName);
                        }*/
                        attachMentPath.add("/upload/"+id+"/" +fileName);
                    }
                }
                //记录上传该文件后的时间
                int finaltime = (int) System.currentTimeMillis();
                System.out.println(finaltime - pre);
            }
        }
		j.setObj(attachMentPath);
		j.setSuccess(true);
		j.setMsg("上传成功!");
		return j;
	}
	@RequestMapping(value = "getDownloadFilePath")
	@ResponseBody
	public  AjaxJson getDownloadFilePath( HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		Map dicMap=new HashMap();
//		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
//		Client client=cache.getCache(token, Client.class);
//		if(client==null||client.getUser()==null){
//			j.setSuccess(false);
//			j.setMsg("未登陆!");
//			return j;
//		}
//		TSUser user=client.getUser();
		String id=request.getParameter("id")==null?"":request.getParameter("id");
		String fileName=request.getParameter("fileName")==null?"":request.getParameter("fileName");
		String type=request.getParameter("type")==null?"":request.getParameter("type");
		String tag=request.getParameter("tag")==null?"":request.getParameter("tag");
		String remark=request.getParameter("remark")==null?"":request.getParameter("remark");
		if(id.trim().equals("")){//||fileName.trim().equals("")
			j.setSuccess(false);
			j.setMsg("文件名称或业务主键id不能为空!");
			return j;
		}
		Map paraMap=new HashMap();
        paraMap.put("businessKey", id);
        if(!fileName.trim().equals(""))
        paraMap.put("fileName", fileName);
        if(!type.trim().equals(""))
            paraMap.put("type", type);
        if(!tag.trim().equals(""))
            paraMap.put("tag", tag);
        if(!remark.trim().equals(""))
            paraMap.put("remark", remark);
        List<Map<String,Object>> attachMents=attachMentService.getAttachment(paraMap);
		j.setObj(attachMents);
		j.setSuccess(true);
		j.setMsg("获取成功!");
		return j;
	}
	/**
	 * 
	* @Title delAttachMent 
	* @Description 删除附件 
	* @param @param id
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "delAttachMent")
	@ResponseBody
	public  AjaxJson delAttachMent(String id, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		int ret=heroService.delete(TBAttachment.class, id);
		j.setObj(ret);
		j.setSuccess(true);
		j.setMsg("获取成功!");
		return j;
	}
}
